<template>
  <view
    class="imageChat-wrapper-box"
    :style="{
      'background-image': `url(${
        toUser.backgroundType != 'video' ? toUser.background : ''
      })`,
    }"
  >
    <u-icon
      @click="goBackRouter"
      class="backIcon"
      name="nav-back"
      color="#000"
      size="44"
    ></u-icon>

    <view class="im-heartbeat-box">
      <text class="heartbeat-title">{{ xvalue.title }}</text>
      <u-line-progress
        style="width: 280rpx; display: flex; align-items: center"
        active-color="#ED447D"
        inactive-color="#FCAEC8"
        :show-percent="false"
        height="12"
        striped
        striped-active
        :percent="xvalue.percent"
      ></u-line-progress>
      <text class="heartbeat-x">{{ xvalue.x }}</text>
      <u-image
        style="margin-bottom: 10rpx"
        :show-loading="false"
        width="28rpx"
        height="24rpx"
        src="@/static/img/love.png"
        mode="widthFix"
      ></u-image>
    </view>
    <view
      class="msg-single-box"
      :style="{ bottom: showActions ? '5%' : '30%' }"
    >
      <view class="content-box">
        <!-- <jp-typewriter
          :text="curReceiveMsg"
          :speed="100"
          @finished="typingFinished"
        ></jp-typewriter> -->
      </view>
      <view
        v-if="showActions"
        class="select-box"
        :class="{ 'fade-in': showActions, 'fade-out': !showActions }"
      >
        <u-button
          @click="sendMessage(action)"
          :disabled="msgLoad || isTyping"
          :customStyle="acCustomStyle"
          class="action"
          type="primary"
          v-for="(action, index) in xvalue.tips"
          :key="index"
          >{{ action }}</u-button
        >
      </view>
    </view>

    <!-- 输入栏 -->
    <!-- <aiInput
      ref="aiInput"
      :socketTask="socketTask"
      v-if="!showActions && !msgLoad && !isTyping"
      @sendMessage="sendMessage"
      @openGiftPop="openGiftPop"
    ></aiInput> -->

    <!-- <countDown ref="countDown" @countDownEnd="countDownEnd"></countDown> -->

    <view
      class="returnStory"
      :style="{ bottom: showActions ? '30rpx' : '150rpx' }"
    >
      <cover-image
        class="returnStoryImg"
        @click="reset"
        src="https://cdn.osisx.com/wenzhu/images/returnStory.png"
      ></cover-image>
    </view>

    <videoBg
      v-if="toUser.backgroundType === 'video'"
      :story_index="story_index"
      :current="current"
      ref="videoBg"
      :storyId="storyId"
      :src="toUser.background"
    >
    </videoBg>
  </view>
</template>

<script>
// #ifdef APP-PLUS-NVUE
const dom = weex.requireModule("dom");
// #endif

import {
  getTalkMessage,
  getTalkByGameAndStory,
  jumpObtain,
  reloadChat,
  sendMessageApi,
} from "@/api/im.js";

import config from "@/config/config.js";
// import myAudio from "@/components/myAudio/index.vue";
// import countDown from "@/components/count-down/index.vue";
import videoBg from "@/components/video-bg/index.vue";
// import aiInput from "@/components/ai-input/index.vue";

import { mapMutations, mapState } from "vuex";

export default {
  components: {
    // myAudio,
    // countDown,
    videoBg,
    // aiInput,
  },
  props: {
    gameId: {
      type: [Number, String],
      default: "",
    },
    storyId: {
      type: [Number, String],
      default: "",
    },
    story_index: {
      type: [Number, String],
      default: "",
    },
    current: {
      type: [Number, String],
      default: "",
    },
    agentId: {
      type: [Number, String],
      default: "",
    },
    socketTask: null,
  },
  watch: {
    agentId: {
      deep: true,
      immediate: true,
      handler(v) {
        if (v) {
          this.getTalk();
        }
      },
    },
  },
  data() {
    return {
      scrollIntoView: "",

      params: {
        //搜索条件
        talkId: "",
        pageSize: 10,
        pageNumber: 1,
      },

      curReceiveMsg: "",
      curMsgList: [], //当前待展示数据
      curMsgIndex: 0, //当前展示数据下标

      toUser: {},

      msgLoad: false,
      isTyping: false,
      lastTime: 0,

      acCustomStyle: {
        color: "#ffffff",
        "font-size": "30rpx",
        "font-weight": "bold",
        "border-radius": "20rpx",
        background: "rgba(98,54,255,0.6)",
        border: "2rpx solid #6236FF",
      },
      canPlay: false,
    };
  },
  computed: {
    xvalue() {
      let xvalue = {
        title: "心动值",
        x: 70,
        goal: 100,
        percent: 70,
        msgValue: 0,
        win: "win1",
        failed: "failed",
        // countDown: false,
        countDownInit: 120,
        tips: [],
        background: "https://cdn.osisx.com/video/pan.mp4",
        backgroundType: "video",
      };
      if (this.toUser.xvalue) {
        xvalue = JSON.parse(this.toUser.xvalue);
        xvalue.percent = Math.round((xvalue.x / xvalue.goal) * 100);

        if (xvalue.backgroundType && xvalue.background) {
          this.toUser.backgroundType = xvalue.backgroundType;
          this.toUser.background = xvalue.background;
        }
        if (xvalue.x >= xvalue.goal) {
          console.log("大于目标值，跳转-----");
          // 结束聊天，自动跳转剧情
          setTimeout(() => {
            this.endStory(xvalue.win);
          }, 5000);
        } else if (xvalue.x < 0) {
          console.log("小于目标值，跳转-----");
          setTimeout(() => {
            this.endStory(xvalue.failed);
          }, 5000);
        }
        this.playCountDown(xvalue.countDown, xvalue.countDownInit);
        return xvalue;
      }
    },
    showActions() {
      let show = false;
      if (this.toUser.xvalue) {
        let xvalue = JSON.parse(this.toUser.xvalue);
        if (xvalue.tips && xvalue.tips.length > 0) {
          show = true;
        }
      }
      return show;
    },
  },
  created() {
    // 通过gameId 和 storyID 获取talkId及对话详情
    if (this.agentId || this.gameId || this.storyId) {
      this.getTalk();
    }
  },
  mounted() {
    this.canPlay = true;
  },
  methods: {
    stopStory(callback) {
      callback(true);
    },
    // 此项是否可播放
    canChangeCurrent(callback) {
      callback(this.canPlay);
    },
    startPlay(callback) {
      // 初始化 getTalk() 暂时无需处理
      callback(true);
    },
    openGiftPop() {
      this.$emit("openGiftPop");
    },

    reset() {
      let params = {
        gameId: this.gameId,
        storyId: this.storyId,
        agentId: this.agentId,
      };
      reloadChat(params).then((res) => {
        if (res.data.success) {
          this.getTalk();
        }
      });
    },

    // 开始倒计时
    playCountDown(countDown, countDownInit) {
      // this.$refs.countDown.play(countDown, countDownInit)
    },
    // 倒计时结束
    countDownEnd() {
      this.endStory(this.xvalue.failed);
    },

    endStory(nextStoryId) {
      this.$emit("endSingleChat", nextStoryId);
    },

    goBackRouter() {
      uni.navigateBack({
        delta: 1,
      });
    },

    async getTalk() {
      let params = {
        gameId: this.gameId,
        storyId: this.storyId,
        agentId: this.agentId,
      };
      getTalkByGameAndStory(params).then((res) => {
        if (res.data.success) {
          this.toUser = res.data.result;
          this.params.talkId = res.data.result.id;

          let results = [
            {
              xvalue: res.data.result.xvalue,
              text: res.data.result.lastTalkMessage,
            },
          ];
          this.setMessage(results);
        }
      });
    },
    sendMessage(mseeage = "") {
      if (!mseeage) {
        return false;
      }
      let currentTime = new Date().getTime();
      if (this.lastTime !== 0) {
        if (currentTime - this.lastTime < 1000) {
          // this.$refs.aiInput.reset();
          this.lastTime = currentTime;
          return;
        }
      }
      this.lastTime = currentTime;
      let msg = {
        toUser: this.toUser.userId2,
        fromUser: this.toUser.userId1,
        storyType: "imageChat",
        messageType: "MESSAGE",
        text: mseeage,
        talkId: this.params.talkId,
        gameId: this.gameId,
        storyId: this.storyId,
      };
      let data = JSON.stringify(msg);

      // this.$refs.aiInput.reset();
      this.msgLoad = true;

      let curResult = [
        {
          text: "正在输入中...",
          xvalue: this.curMsgList[this.curMsgIndex].xvalue,
        },
      ];
      this.setMessage(curResult);
      sendMessageApi(data).then((res) => {
        if (res.data.success) {
          this.msgLoad = false;
          this.setMessage(res.data.result);
        } else {
          this.msgLoad = false;
        }
      });
    },

    /**
     * @param {Object} results
     */
    setMessage(results) {
      console.log(results, "-------------results");
      this.curMsgList = results; //当前待展示数据
      this.curMsgIndex = 0; //当前展示数据下标

      this.isTyping = true; //正在打印文字
      this.$set(this, "curReceiveMsg", this.curMsgList[this.curMsgIndex].text);
      this.$set(
        this.toUser,
        "xvalue",
        this.curMsgList[this.curMsgIndex].xvalue
      );
      console.log(this.curReceiveMsg, "setMessage");
    },
    typingFinished() {
      // 打字完成后的回调函数
      console.log("Typing finished");
      this.isTyping = false; //正在打印文字
      if (
        this.curMsgList.length > 1 &&
        this.curMsgIndex + 1 < this.curMsgList.length
      ) {
        this.curMsgIndex = this.curMsgIndex + 1;

        this.$set(
          this,
          "curReceiveMsg",
          this.curMsgList[this.curMsgIndex].text
        );
        this.$set(
          this.toUser,
          "xvalue",
          this.curMsgList[this.curMsgIndex].xvalue
        );
      }
    },
  },
};
</script>


<style lang="scss" scoped>
@import "./index.scss";
</style>